#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

bool is_valid_address(const char *input) {
    // 简单验证是否为合法的十六进制数
    const char *hex_chars = "0123456789abcdefABCDEF";
    while (*input != '\0') {
        if (strchr(hex_chars, *input) == NULL) {
            return false;
        }
        input++;
    }
    return true;
}

int main() {
    int a = 10;
    int *b = NULL;
    
    // 打印变量 a 的内存地址
    printf("The address of variable a is: %p\n", &a);

    // 用户输入 a 的内存地址
    char input[20]; // 假设输入的地址长度不超过 20
    printf("Please enter the memory address of variable a: ");
    fgets(input, sizeof(input), stdin);
    
    // 移除末尾的换行符
    input[strcspn(input, "\n")] = 0;

    if (!is_valid_address(input)) {
        printf("Invalid address entered.\n");
        return 1;
    }

    // 将输入的十六进制字符串转换为地址
    void *address = (void *)strtoull(input, NULL, 16);
    b = (int *)address;

    // 检查 b 是否指向有效地址
    if (b != (int *)address) {
        printf("Failed to cast address to int*.\n");
        return 1;
    }

    // 往栈底方向打印 10 个地址及存储的数据
    for (int i = 0; i < 10; i++) {
        void *current_address = (char *)b - i * sizeof(int);
        int *data = (int *)current_address;
        printf("Address: %p, Data: %c\n", current_address, (char)*data); 
        // 检查是否为合法地址
/*        if (current_address >= &a && current_address <= &a + sizeof(a)) {
            printf("Address: %p, Data: %c\n", current_address, (char)*data);
        } else {
            printf("Address: %p, Data: (invalid address)\n", current_address);
	    
        }
*/	
    }

    return 0;
}
